﻿package net.wangit.dev.dataprivilege;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.DomainAction;
import net.wangit.dev.LockUtil;
import net.wangit.dev.VersionUtil;
import net.wangit.dev.version.DataPrivilegeVersion;
import net.wangit.dev.version.Version;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.user.privilege.DataPrivilegeCache;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;


public class SaveDataPrivilegeAction extends DomainAction {

	private static Version version = new DataPrivilegeVersion();

	public SaveDataPrivilegeAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String newId = ac.getRequestParameter("dp.dpid");
		if (!Checker.isEmpty(newId))
			newId = StringUtil.clearSpace(newId.toLowerCase());
		format(ac, newId);
		super.doAction(db, ac);
		ac.setSessionAttribute(
				"net.wangit.dev.dataprivilege.DataPrivilegeUI.dpid", newId);
		String oldId = ac.getRequestParameter("dp.dpid.k");
		if (!Checker.isEmpty(oldId) && oldId.equals(newId))
			ac.getActionResult().setScript(null);
		DataPrivilegeCache.clearAll(domain);
		DataPrivilegeReferenceHelper.update(db, domain, oldId, newId);
		VersionUtil.saveVersion(ac, version, domain, newId);
	}

	private void format(ActionContext ac, String dpid) {
		List<Table> tables = ac.getTables();
		for (int i = 0; i < tables.size(); i++) {
			Table table = tables.get(i);
			if ("DPCONFIG".equals(table.getTableName()))
				formatConfig(ac, table.getRows(), dpid);
			else if ("DP".equals(table.getTableName()))
				formatEnumeration(table.getRows(), dpid);
		}

	}

	private void formatConfig(ActionContext ac, List<ColumnRow> rows,
			String dpid) {
		if (rows.size() > 0) {
			ColumnRow row = rows.get(0);
			row.set("dpid", dpid);
			LockUtil.setFields(ac, row, "dp");
		}
	}

	private void formatEnumeration(List<ColumnRow> rows, String dpid) {
		for (int i = 0; i < rows.size(); i++) {
			ColumnRow row = rows.get(i);
			row.set("dpid", dpid);
		}

	}

}
